﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace LiteFramework.Security
{
    public enum HashType
    {
        SHA1,
        MD5,
    }
    /// <summary>
    /// MD5 / HAS
    /// </summary>
    public class MD5 : SecurityAbs
    {
        /// <summary>
        /// 字符编码。默认为：Encoding.Default
        /// </summary>
        private static Encoding encoding { get { return Encoding.Default; } }


        /// <summary>
        /// 计算文本哈希值
        /// <para>　　SHA1CryptoServiceProvider.ComputeHash()</para>
        /// </summary>
        /// <param name="plainStr"></param>
        /// <returns></returns>
        public static string CreateHash(string plainStr)
        {
            return CreateHashExt(plainStr, HashType.SHA1);
        }

        /// <summary>
        /// 获取MD5密文
        /// <para>　　MD5CryptoServiceProvider.ComputeHash()</para>
        /// </summary>
        /// <param name="plainStr"></param>
        /// <returns></returns>
        public static string CreateHash_MD5(string plainStr)
        {
            return CreateHashExt(plainStr, HashType.MD5);
        }


        /// <summary>
        /// 生成哈希值
        /// </summary>
        /// <param name="plainStr"></param>
        /// <param name="hashType"></param>
        /// <returns></returns>
        public static byte[] CreateHash(string plainStr, HashType hashType)
        {
            return CreateHash(encoding.GetBytes(plainStr), hashType);
        }

        /// <summary>
        /// 生成哈希值
        /// </summary>
        /// <param name="plainStr"></param>
        /// <param name="hashType"></param>
        /// <returns></returns>
        public static string CreateHashExt(string plainStr, HashType hashType)
        {
            byte[] hash = CreateHash(encoding.GetBytes(plainStr), hashType);

            //StringBuilder passwordbullder = new StringBuilder(32);
            //foreach (byte hashByte in hash)
            //{
            //    //passwordbullder.Append(hashByte.ToString("x2"));
            //    passwordbullder.AppendFormat("{0:x2}", hashByte);
            //}
            //return passwordbullder.ToString();

            return Convert.ToBase64String(hash);
        }

        /// <summary>
        /// 生成哈希值
        /// </summary>
        /// <param name="plainStr"></param>
        /// <param name="hashType"></param>
        /// <returns></returns>
        public static byte[] CreateHash(byte[] plainStr, HashType hashType)
        {
            HashAlgorithm algorithm = null;
            if (hashType == HashType.SHA1)
            {
                algorithm = SHA1CryptoServiceProvider.Create();
            }
            else
            {
                algorithm = MD5CryptoServiceProvider.Create();
            }

            byte[] hash = algorithm.ComputeHash(plainStr);

            algorithm.Clear();

            return hash;
        }
    }
}